/**
 * 功能：初始化数据
 * @param {Object} paramObjName：初始化参数对象的实例名 
 * @param {Object} updateUrl: 更新读取记录的URL地址 
 * @param {Object} deleteUrl: 删除数据对应的URL地址 
 * @param {Object} tableId：列表数据表格的ID 
 * @param {Object} searchID：查询对应的id 
 * @param {Object} resetSearchID：查询重置的id 
 * @param {Object} searchFormID:普通查找对应的form的ID 
 * @param {Object} addDataFormId:添加数据对应Form的ID 
 * @param {Object} addDialogWidth:添加数据对应对话框的宽度
 * @param {Object} addDialogHeight:添加数据对应对话框的高度
 * @param {Object} ctx:页面对应的上下文
 * @param {Object} addDialogTitle:添加数据对应对话框的标题
 */
function initParams(initData) {
	this.paramObjName = initData.paramObjName;
	this.updateUrl = initData.updateUrl;
	this.deleteUrl = initData.deleteUrl;
	this.addDataFormId = initData.addDataFormId || 'addDataForm';
	this.searchID = initData.searchID || 'search';
	this.resetSearchID = initData.resetSearchID || 'resetSearch';
	this.searchFormID = initData.searchFormID || 'searchForm';
	this.tableId = initData.tableId || 'listTable';
	this.addDialogWidth = initData.addDialogWidth;
	this.addDialogHeight = initData.addDialogHeight;
	this.ctx = initData.ctx;
	this.addDialogTitle = initData.addDialogTitle;
	this.saveButton=initData.saveButton||i18n.saveButton;
	this.cancelButton=initData.cancelButton||i18n.cancelButton;
	this.showDialogId = initData.showDialogId || 'firstLevelDialog';
}
function getUrlParamValue(paramName) {
	var url = location.href;
	var params = url.replace("?","?&").split("&");
	for(var i=1;i<params.length;i++) {
		if (params[i].indexOf(paramName+"=") == 0) {
			return params[i].substring((paramName+"=").length,params[i].length);
		}
	}
}
/**
 * 初始化查询
 * @param {Object} paramObj ： 初始化参数对象的实例名 
 */
function init(paramObj){
	$('#'+paramObj.searchFormID).show();
	//普通查询
	$("#"+paramObj.searchID).click(function(){
		//$("#"+paramObj.searchID).attr('disabled',true);
		queryData(paramObj);
	});	
	//普通查询清空操作
	$("#"+paramObj.resetSearchID).click(function(){
		$("#"+paramObj.searchFormID+" input").val("");
		$("#"+paramObj.searchFormID).find("select").each(function(){
			var value = $(this).combobox('getData')[0].value;
			$(this).combobox('select',value);
		});
	});
}

function queryData(paramObj){
	if($('#'+paramObj.searchFormID).form('validate')){
		var queryParam = $("#"+paramObj.searchFormID).serialize();
		queryParam = decodeURIComponent(queryParam.replace(/\+/g," "),true);
		var queryParams = {};
		if(queryParam != undefined){
			var queryParamSplit = queryParam.split("&");
			for(var i=0;i<queryParamSplit.length;i++){
				var queryNameValue = queryParamSplit[i].split('=');
				queryParams[queryNameValue[0]] = queryNameValue[1];
			}
		}
		$('#'+paramObj.tableId).datagrid('load',queryParams);
	}
}
/**
 * 打开添加数据的页面的对话框
 * @param {Object} paramObj ： 对应的列表对象
 * @param {Object} id ： 数据记录的ID
 * @param {Object} successcallback ：添加数据成功后的回调函数
 * @param {Object} failurecallback ： 添加数据失败后的回调函数
 */
function openDataDialog(paramObj,id,successcallback,failurecallback){
	if(id == undefined){
		id='';
	}
	var sign = false;
	top.$('#'+paramObj.showDialogId).dialog({    
	    title:paramObj.addDialogTitle,  
	    iconCls:'icon-view',
	    width: paramObj.addDialogWidth,    
	    height: paramObj.addDialogHeight,    
	    closed: false,    
	    inline : true,
	    cache: false,    
	    href: paramObj.updateUrl+id,    
	    modal: true,
		extractor : function(data){
			if($.trim(data) == "unLogin"){
				var msn = ''||i18n[''];
				msn = msn||i18n[data];
				if(msn != undefined){
					top.$('#'+paramObj.showDialogId).dialog('close');
					$.messager.alert('提示',msn,'info',function(){top.location=paramObj.ctx;});
					return '';
				}
			}
			return data;
		},
	    buttons : [{text:paramObj.saveButton,
	    		id:'saveEntityBt',
				iconCls:'icon-ok',
				handler:function(){
					saveEntity(paramObj,'saveEntityBt',successcallback,failurecallback);
				}
			},{
				text:paramObj.cancelButton,
				iconCls:'icon-cancel',
				handler:function(){
					top.$('#'+paramObj.showDialogId).dialog('close');
				}}]
	});
}
/**
 * 添加、更新保存数据
 * @param {Object} paramObj:表格对应的初始化对象
 * @param {Object} opBtId: 代表保存数据按钮对应的ID，进行防止重复提交的作用
 * @param {Object} successcallback：在调用添加成功后调用的初始化回调方法
 * @param {Object} failurecallback：在调用添加失败后调用的初始化回调方法
 */
function saveEntity(paramObj,opBtId,successcallback,failurecallback){
	var msn = ''||i18n[''];
	if(top.$('#'+paramObj.addDataFormId).form('validate')){
		top.$('#'+opBtId).linkbutton('disable');
		$.ajax({
			type: "POST",
			timeout:20000,
			url:  top.$('#'+paramObj.addDataFormId).attr("action"),
			data:top.$("#"+paramObj.addDataFormId).serialize(),
			success: function(data,res){
				var result = $.trim(data);
				if(result == "unLogin"){
					msn = msn||i18n[result];
					if(msn != undefined){
						//top.$('#'+paramObj.showDialogId).dialog('close');
						top.$.messager.alert('提示',msn,'info',function(){top.location=paramObj.ctx;});
						return ;
					}
				}
				msn = msn||i18n[data];	
				if(msn == undefined){
					top.$.messager.alert('提示',data,'info',function(){top.$('#'+opBtId).linkbutton('enable');});
				}else if(msn)	{	
					top.$.messager.alert('提示',msn,'info',function(){$('#'+paramObj.tableId).datagrid('reload');top.$('#'+paramObj.showDialogId).dialog('close');});
				}
				if(successcallback != undefined){
					successcallback();
				}
			},
			error: function(res){
				top.$.messager.alert('提示',i18n.requestError,'error');
				top.$('#'+opBtId).linkbutton('enable');
				if(failurecallback != undefined){
					failurecallback();
				}
			}
		});
	}
}
/**
 * 选择记录更新数据
 * @param {Object} paramObj:表格对应的初始化对象
 * @param {Object} successcallback：在调用更新成功后调用的初始化回调方法
 * @param {Object} failurecallback：在调用更新失败后调用的初始化回调方法
 */
function updateData(paramObj,successcallback,failurecallback){
	var records = $('#'+paramObj.tableId).datagrid('getSelections');
	if(records.length != 1){
		$.messager.alert('提示',"请选择一条记录！",'info');
	}else{
		var record = records[0];
		openDataDialog(paramObj,record.id,successcallback,failurecallback);
	}
}
/**
 * 根据选择的记录进行删除数据
 * @param {Object} paramObj ： 表格对应的初始化对象
 * @param {Object} successcallback：在调用删除成功后调用的初始化回调方法
 * @param {Object} failurecallback：在调用删除失败后调用的初始化回调方法
 */
function deleteData(paramObj,successcallback,failurecallback){
	var records = $('#'+paramObj.tableId).datagrid('getSelections');
	if(records.length < 1){
		$.messager.alert('提示',"请选择记录！",'info');
	}else{
		var deleteIds = '';
		for(var i=0;i<records.length-1;i++){
			deleteIds += records[i].id+",";
		}
		deleteIds += records[records.length-1].id;
		$.messager.confirm('提示',"确定删除这条记录吗？",function(result){
			if(result){
				var msn = ''||i18n[''];
				$.ajax({
					type: "get",
					url:  paramObj.deleteUrl,
					data:'deleteIds='+deleteIds,
					async : false,
					success: function(data,res){
						msn = msn||i18n[data];	
						if(msn == undefined){
							$.messager.alert('提示',i18n.serverError,'error');
						}else if(msn)	{
							if(data == "unLogin"){
								if(msn != undefined){
									$.messager.alert('提示',msn,'info',function(){top.location=paramObj.ctx;});
									return ;
								}
							}
							// TODO 使用动态提醒
							//animateShowMsg('ok', msn);
							if(successcallback != undefined){
								successcallback();
							}
							$.messager.alert('提示',msn,'info',function(){$('#'+paramObj.tableId).datagrid('reload');});
						}
					},
					error: function(res){
						$.messager.alert('提示',i18n.requestError,'error');
						if(failurecallback != undefined){
							failurecallback();
						}
					}
				});
			}
		});
	}
}
/**   
 * by 冯亚
 * 检测指定容器还可以输入多少个字
 * tipId:提示框Id
 * countNum:共可以输入的字数
 * id:输入框（文本域Id）
 */
function checkLength(tipId,countNum,id){
    var curLength = document.getElementById(id).value.length;
    if (curLength>countNum){
        document.getElementById(id).value = document.getElementById(id).value.substr(0,countNum);
        // 解决回车双字符的问题
        if(document.getElementById(id).value.length>countNum){
        	document.getElementById(id).value = document.getElementById(id).value.substr(0,countNum-1);
        	curLength = countNum;	
        }
        curLength = countNum;	
    }
	document.getElementById(tipId).innerHTML = countNum-document.getElementById(id).value.length;
}
